<?php


namespace app\api\controller\v20;


use app\api\controller\v2\Auth;
use app\common\cachemodel\ZlAstrExercise;
use app\common\cachemodel\ZlAstrExerciseRecord;
use app\common\lib\Util;
use think\Env;

/**
 * @version 2.4.0
 * Class StarActiv
 * @package app\api\controller\v20
 */
class StarActiv extends Auth
{
    /**
     * 每关 每一题 分数
     * @var array
     */
    private $questionScore = [
        1 => 10,
        2 => 20,
        3 => 30,
    ];

    /**
     * 每关 通关 分数【总分】
     * @var array
     */
    private $levelSuccessScore = [
        1 => 0,
        2 => 0,
        3 => 300,
    ];

    /**
     * 获取题目
     */
    public function getQuestion()
    {
        $type = input('type/d', 1);
        $index = input('index/d', 0);
        $option = trim(input('option/s', ''));
        $tel = input('tel/s', '');
        $loveOption = input('love_option/s', '');

        $uid = (int)$this->user['id'];
        $questionModel = new ZlAstrExercise();
        $userAnswerModel = new ZlAstrExerciseRecord();

        // 获取用户当前答题状态信息
        $userAnswerInfo = $userAnswerModel->getInfoById($uid);
        if ($type === 3)
        {
            $resData = $this->getScore($userAnswerInfo);
            return show(config('code.success'), '请求成功', $resData);
        }
        // 获取当前用户答题进度
        if (!$userAnswerInfo)
        {   // 初始化答题进度
            // 获取第一关 随机20题
            $questionIds = $questionModel->randomGetQuestionId(1, 30, 1);

            if (!$questionIds)
            {
                return show(config('code.error'), '服务异常；请稍后再试～');
            }

            $content1 = [
                'question' => $questionIds,
                'start_time' => $this->request->time(), // 开始答题时间
                'index' => 1, // 当前第几题
                'max_question' => 30,  // 总题目数
                'max_answer_time' => 40, // 最大答题时长
                'answer' => [] // 答案信息
            ];

            $cacheData = [
                'create_time' => $this->request->time(),
                'uid' => $uid,
                'name' => $this->user['nickname'],
                'avatar' => $this->user['avatar'],
                'content1' => json_encode($content1, JSON_UNESCAPED_UNICODE),
                'content2' => '',
                'content3' => '',
                'content4' => '',
                'grade1' => 0,
                'grade2' => 0,
                'grade3' => 0,
                'grade4' => 0,
                'grade' => 0,
                'level' => 1,
                'status' => 1,
                'answer_time' => 0, //答题耗时 总时长
            ];

            $userAnswerModel->setCacheData($cacheData, $uid);

            $questionId = $questionIds[$content1['index'] - 1];// 获取当前题目ID

            $resData = $this->getResultData($content1, $questionId, 10);
        } else
        {
            switch ($userAnswerInfo['level'])
            {
                case 1:
                    if ($type === 1)
                    {   // 提交答案 ｜ 获取题目 ｜ 结果
                        $content1 = json_decode($userAnswerInfo['content1'], true);
                        if ((int)$userAnswerInfo['status'] === 2 || (isset($content1['answer_total_time']) && $content1['answer_total_time']))
                        {
                            $resData = [
                                'step' => 11,
                                'index_score' => (int)$userAnswerInfo['grade1'],
                                'total_score' => (int)$userAnswerInfo['grade'],
                                'answer_right' => $content1['answer_right_num'],
                                'answer_wrong' => $content1['answer_wrong_num'],
                                'timeout_num' => $content1['answer_timeout_num'],
                                'max_question' => $content1['max_question'],
                                'isSuccessful' => (int)$userAnswerInfo['status'] === 1, // 是否通关
                                'score_list' => [
                                    [
                                        'grade' => (int)$userAnswerInfo['grade1'],
                                        'status' => 3
                                    ],
                                    [
                                        'grade' => '一',
                                        'status' => 0
                                    ],
                                    [
                                        'grade' => '一',
                                        'status' => 0
                                    ],
                                    [
                                        'grade' => '一',
                                        'status' => 0
                                    ],
                                ],
                            ];
                            break;
                        }
                        if ($index && $option && $index <= $content1['index'])
                        {   // 提交答案
                            $res = $this->nextQuestion($content1, $index, $option, 10);
                            if ($res['updateCache'])
                            {   // 是否更新缓存
                                $userAnswerInfo['content1'] = json_encode($res['content'], JSON_UNESCAPED_UNICODE);
                                if ($res['isOver'])
                                {
                                    $score = $res['content']['answer_right_num'] * $this->questionScore[1];//每题5分
                                    $userAnswerInfo['grade1'] = $score; // 第一关分数
                                    $userAnswerInfo['grade'] += $score; // 总分数
                                    $userAnswerInfo['answer_time'] += $res['content']['answer_total_time']; // 答题总时长
                                    // if ($score < $this->levelSuccessScore[1]) // 当前关卡
                                    if ($userAnswerInfo['grade'] < $this->levelSuccessScore[1]) // 总分
                                    {   // 通关失败
                                        $userAnswerInfo['status'] = 2;//挑战结束
                                    }

                                    $id = $userAnswerModel->insertGetId($userAnswerInfo);

                                    $userAnswerInfo['id'] = $id;

                                    $resData = [
                                        'step' => 11,
                                        'index_score' => (int)$score,
                                        'total_score' => (int)$userAnswerInfo['grade'],
                                        'answer_right' => $res['content']['answer_right_num'],
                                        'answer_wrong' => $res['content']['answer_wrong_num'],
                                        'timeout_num' => $res['content']['answer_timeout_num'],
                                        'max_question' => $res['content']['max_question'],
                                        'isSuccessful' => (int)$userAnswerInfo['status'] === 1, // 是否通关
                                        'score_list' => [
                                            [
                                                'grade' => (int)$userAnswerInfo['grade1'],
                                                'status' => 3
                                            ],
                                            [
                                                'grade' => '一',
                                                'status' => 0
                                            ],
                                            [
                                                'grade' => '一',
                                                'status' => 0
                                            ],
                                            [
                                                'grade' => '一',
                                                'status' => 0
                                            ],
                                        ],
                                    ];
                                    $userAnswerModel->setCacheData($userAnswerInfo, $uid); // 更新缓存
                                    $userAnswerModel->changeRankingScore($uid, (int)$userAnswerInfo['grade'], $userAnswerInfo['answer_time']);
                                    break;
                                } else
                                {
                                    $userAnswerModel->setCacheData($userAnswerInfo, $uid); // 更新缓存
                                }
                            }
                            $resData = $res['resData'];
                        } else
                        {   // 获取题目
                            $isNext = ($this->request->time() - $content1['start_time']) >= $content1['max_answer_time']; // 是否下一题
                            if ($isNext)
                            {   // 下一题
                                $res = $this->nextQuestion($content1, $content1['index'], '', 10);
                                if ($res['updateCache'])
                                {   // 是否更新缓存
                                    $userAnswerInfo['content1'] = json_encode($res['content'], JSON_UNESCAPED_UNICODE);
                                    if ($res['isOver'])
                                    {
                                        $score = $res['content']['answer_right_num'] * $this->questionScore[1];//每题5分
                                        $userAnswerInfo['grade1'] = $score; // 第一关分数
                                        $userAnswerInfo['grade'] += $score; // 总分数
                                        $userAnswerInfo['answer_time'] += $res['content']['answer_total_time']; // 答题总时长
                                        // if ($score < $this->levelSuccessScore[1]) // 当前关卡
                                        if ($userAnswerInfo['grade'] < $this->levelSuccessScore[1]) // 总分
                                        {   // 通关失败
                                            $userAnswerInfo['status'] = 2;//挑战结束
                                        }

                                        $id = $userAnswerModel->insertGetId($userAnswerInfo);

                                        $userAnswerInfo['id'] = $id;

                                        $resData = [
                                            'step' => 11,
                                            'index_score' => (int)$score,
                                            'total_score' => (int)$userAnswerInfo['grade'],
                                            'answer_right' => $res['content']['answer_right_num'],
                                            'answer_wrong' => $res['content']['answer_wrong_num'],
                                            'timeout_num' => $res['content']['answer_timeout_num'],
                                            'max_question' => $res['content']['max_question'],
                                            'isSuccessful' => (int)$userAnswerInfo['status'] === 1, // 是否通关
                                            'score_list' => [
                                                [
                                                    'grade' => (int)$userAnswerInfo['grade1'],
                                                    'status' => 3
                                                ],
                                                [
                                                    'grade' => '一',
                                                    'status' => 0
                                                ],
                                                [
                                                    'grade' => '一',
                                                    'status' => 0
                                                ],
                                                [
                                                    'grade' => '一',
                                                    'status' => 0
                                                ],
                                            ],
                                        ];
                                        $userAnswerModel->setCacheData($userAnswerInfo, $uid); // 更新缓存
                                        $userAnswerModel->changeRankingScore($uid, (int)$userAnswerInfo['grade'], $userAnswerInfo['answer_time']);// 更新排行榜信息
                                        break;
                                    } else
                                    {
                                        $userAnswerModel->setCacheData($userAnswerInfo, $uid); // 更新缓存
                                    }
                                }
                                $resData = $res['resData'];
                            } else
                            {   // 当前题
                                $resData = $this->getResultData($content1, $content1['question'][$content1['index'] - 1], 10);
                            }
                        }
                    } else
                    {   // 进入下一关
                        $content1 = json_decode($userAnswerInfo['content1'], true);
                        if (!isset($content1['answer_total_time']) && (int)$userAnswerInfo['status'] === 1)
                        {
                            return show(config('code.error'), '请求异常');
                        }

                        // if ((int)$userAnswerInfo['status'] === 2 || $userAnswerInfo['grade1'] < $this->levelSuccessScore[1]) // 当前关卡分数满足条件
                        if ((int)$userAnswerInfo['status'] === 2 || $userAnswerInfo['grade'] < $this->levelSuccessScore[1]) // 总分满足条件
                        {
                            return show(config('code.error'), '当前挑战已结束');
                        }
                        // 初始化第二关答题进度
                        // 获取第二关 随机10题
                        $questionIds = $questionModel->randomGetQuestionId(2, 10, 1);

                        if (!$questionIds)
                        {
                            return show(config('code.error'), '服务异常；请稍后再试～');
                        }

                        $content2 = [
                            'question' => $questionIds,
                            'start_time' => $this->request->time(), // 开始答题时间
                            'index' => 1, // 当前第几题
                            'max_question' => 10,  // 总题目数
                            'max_answer_time' => 80, // 最大答题时长
                            'answer' => [] // 答案信息
                        ];
                        $questionId = $questionIds[$content2['index'] - 1];// 获取当前题目ID

                        $userAnswerInfo['content2'] = json_encode($content2, JSON_UNESCAPED_UNICODE);
                        $userAnswerInfo['level']++;
                        $userAnswerModel->setCacheData($userAnswerInfo, $uid); // 更新缓存

                        $resData = $this->getResultData($content2, $questionId, 20);
                    }
                    break;
                case 2:
                    if ($type === 1)
                    {   // 提交答案 ｜ 获取题目 ｜ 结果
                        $content2 = json_decode($userAnswerInfo['content2'], true);
                        if ((int)$userAnswerInfo['status'] === 2 || (isset($content2['answer_total_time']) && $content2['answer_total_time']))
                        {
                            $resData = [
                                'step' => 21,
                                'index_score' => (int)$userAnswerInfo['grade1'],
                                'total_score' => (int)$userAnswerInfo['grade'],
                                'answer_right' => $content2['answer_right_num'],
                                'answer_wrong' => $content2['answer_wrong_num'],
                                'timeout_num' => $content2['answer_timeout_num'],
                                'max_question' => $content2['max_question'],
                                'isSuccessful' => (int)$userAnswerInfo['status'] === 1, // 是否通关
                                'score_list' => [
                                    [
                                        'grade' => (int)$userAnswerInfo['grade1'],
                                        'status' => 3
                                    ],
                                    [
                                        'grade' => (int)$userAnswerInfo['grade2'],
                                        'status' => 3
                                    ],
                                    [
                                        'grade' => '一',
                                        'status' => 0
                                    ],
                                    [
                                        'grade' => '一',
                                        'status' => 0
                                    ],
                                ],
                            ];
                            break;
                        }
                        if ($index && $option && $index <= $content2['index'])
                        {   // 提交答案
                            $res = $this->nextQuestion($content2, $index, $option, 20);
                            if ($res['updateCache'])
                            {   // 是否更新缓存
                                $userAnswerInfo['content2'] = json_encode($res['content'], JSON_UNESCAPED_UNICODE);
                                if ($res['isOver'])
                                {
                                    $score = $res['content']['answer_right_num'] * $this->questionScore[$userAnswerInfo['level']];//每题5分
                                    $userAnswerInfo['grade2'] = $score; // 第二关分数
                                    $userAnswerInfo['grade'] += $score; // 总分数
                                    $userAnswerInfo['answer_time'] += $res['content']['answer_total_time']; // 答题总时长
                                    // if ($score < $this->levelSuccessScore[$userAnswerInfo['level']]) // 当前关卡 分数
                                    if ($userAnswerInfo['grade'] < $this->levelSuccessScore[$userAnswerInfo['level']]) // 总分
                                    {   // 通关失败
                                        $userAnswerInfo['status'] = 2;//挑战结束
                                    }

                                    // 更新
                                    $userAnswerModel->where('id', $userAnswerInfo['id'])->update([
                                        'update_time' => $this->request->time(),
                                        'grade2' => $userAnswerInfo['grade2'],
                                        'grade' => $userAnswerInfo['grade'],
                                        'content2' => $userAnswerInfo['content2'],
                                        'answer_time' => $userAnswerInfo['answer_time'],
                                        'status' => $userAnswerInfo['status'],
                                        'level' => $userAnswerInfo['level']
                                    ]);

                                    $resData = [
                                        'step' => 21,
                                        'index_score' => (int)$score,
                                        'total_score' => (int)$userAnswerInfo['grade'],
                                        'answer_right' => $res['content']['answer_right_num'],
                                        'answer_wrong' => $res['content']['answer_wrong_num'],
                                        'timeout_num' => $res['content']['answer_timeout_num'],
                                        'max_question' => $res['content']['max_question'],
                                        'isSuccessful' => (int)$userAnswerInfo['status'] === 1, // 是否通关
                                        'score_list' => [
                                            [
                                                'grade' => (int)$userAnswerInfo['grade1'],
                                                'status' => 3
                                            ],
                                            [
                                                'grade' => (int)$userAnswerInfo['grade2'],
                                                'status' => 3
                                            ],
                                            [
                                                'grade' => '一',
                                                'status' => 0
                                            ],
                                            [
                                                'grade' => '一',
                                                'status' => 0
                                            ],
                                        ],
                                    ];
                                    $userAnswerModel->setCacheData($userAnswerInfo, $uid); // 更新缓存
                                    $userAnswerModel->changeRankingScore($uid, (int)$userAnswerInfo['grade'], $userAnswerInfo['answer_time']); // 更新排行榜信息
                                    break;
                                } else
                                {
                                    $userAnswerModel->setCacheData($userAnswerInfo, $uid); // 更新缓存
                                }
                            }
                            $resData = $res['resData'];
                        } else
                        {   // 获取题目
                            $isNext = ($this->request->time() - $content2['start_time']) >= $content2['max_answer_time']; // 是否下一题
                            if ($isNext)
                            {   // 下一题
                                $res = $this->nextQuestion($content2, $content2['index'], '', 20);
                                if ($res['updateCache'])
                                {   // 是否更新缓存
                                    $userAnswerInfo['content2'] = json_encode($res['content'], JSON_UNESCAPED_UNICODE);
                                    if ($res['isOver'])
                                    {
                                        $score = $res['content']['answer_right_num'] * $this->questionScore[$userAnswerInfo['level']];//每题5分
                                        $userAnswerInfo['grade2'] = $score; // 第二关分数
                                        $userAnswerInfo['grade'] += $score; // 总分数
                                        $userAnswerInfo['answer_time'] += $res['content']['answer_total_time']; // 答题总时长
                                        // if ($score < $this->levelSuccessScore[$userAnswerInfo['level']]) // 当前关卡 分数
                                        if ($userAnswerInfo['grade'] < $this->levelSuccessScore[$userAnswerInfo['level']]) // 总分
                                        {   // 通关失败
                                            $userAnswerInfo['status'] = 2;//挑战结束
                                        }

                                        // 更新
                                        $userAnswerModel->where('id', $userAnswerInfo['id'])->update([
                                            'update_time' => $this->request->time(),
                                            'grade2' => $userAnswerInfo['grade2'],
                                            'grade' => $userAnswerInfo['grade'],
                                            'content2' => $userAnswerInfo['content2'],
                                            'answer_time' => $userAnswerInfo['answer_time'],
                                            'status' => $userAnswerInfo['status'],
                                            'level' => $userAnswerInfo['level']
                                        ]);

                                        $resData = [
                                            'step' => 21,
                                            'index_score' => (int)$score,
                                            'total_score' => (int)$userAnswerInfo['grade'],
                                            'answer_right' => $res['content']['answer_right_num'],
                                            'answer_wrong' => $res['content']['answer_wrong_num'],
                                            'timeout_num' => $res['content']['answer_timeout_num'],
                                            'max_question' => $res['content']['max_question'],
                                            'isSuccessful' => (int)$userAnswerInfo['status'] === 1, // 是否通关
                                            'score_list' => [
                                                [
                                                    'grade' => (int)$userAnswerInfo['grade1'],
                                                    'status' => 3
                                                ],
                                                [
                                                    'grade' => (int)$userAnswerInfo['grade2'],
                                                    'status' => 3
                                                ],
                                                [
                                                    'grade' => '一',
                                                    'status' => 0
                                                ],
                                                [
                                                    'grade' => '一',
                                                    'status' => 0
                                                ],
                                            ],
                                        ];
                                        $userAnswerModel->setCacheData($userAnswerInfo, $uid); // 更新缓存
                                        $userAnswerModel->changeRankingScore($uid, (int)$userAnswerInfo['grade'], $userAnswerInfo['answer_time']); // 更新排行榜信息
                                        break;
                                    } else
                                    {
                                        $userAnswerModel->setCacheData($userAnswerInfo, $uid); // 更新缓存
                                    }
                                }
                                $resData = $res['resData'];
                            } else
                            {   // 当前题
                                $resData = $this->getResultData($content2, $content2['question'][$content2['index'] - 1], 20);
                            }
                        }
                    } else
                    {   // 进入下一关
                        $content2 = json_decode($userAnswerInfo['content2'], true);
                        if (!isset($content2['answer_total_time']) && (int)$userAnswerInfo['status'] === 1)
                        {
                            return show(config('code.error'), '请求异常');
                        }

                        // if ((int)$userAnswerInfo['status'] === 2 || $userAnswerInfo['grade2'] < $this->levelSuccessScore[$userAnswerInfo['level']]) // 当前关卡分数满足条件
                        if ((int)$userAnswerInfo['status'] === 2 || $userAnswerInfo['grade'] < $this->levelSuccessScore[$userAnswerInfo['level']]) // 总分满足条件
                        {
                            return show(config('code.error'), '当前挑战已结束');
                        }
                        // 初始化第三关答题进度
                        // 获取第三关 随机10题
                        $questionIds = $questionModel->randomGetQuestionId(3, 10, 1);

                        if (!$questionIds)
                        {
                            return show(config('code.error'), '服务异常；请稍后再试～');
                        }

                        $content3 = [
                            'question' => $questionIds,
                            'start_time' => $this->request->time(), // 开始答题时间
                            'index' => 1, // 当前第几题
                            'max_question' => 10,  // 总题目数
                            'max_answer_time' => 120, // 最大答题时长
                            'answer' => [] // 答案信息
                        ];
                        $questionId = $questionIds[$content3['index'] - 1];// 获取当前题目ID

                        $userAnswerInfo['content3'] = json_encode($content3, JSON_UNESCAPED_UNICODE);
                        $userAnswerInfo['level']++;
                        $userAnswerModel->setCacheData($userAnswerInfo, $uid); // 更新缓存

                        $resData = $this->getResultData($content3, $questionId, 30);
                    }
                    break;
                case 3:
                    if ($type === 1)
                    {   // 提交答案 ｜ 获取题目 ｜ 结果
                        $content3 = json_decode($userAnswerInfo['content3'], true);
                        if ((int)$userAnswerInfo['status'] === 2 || (isset($content3['answer_total_time']) && $content3['answer_total_time']))
                        {
                            $resData = [
                                'step' => 31,
                                'index_score' => (int)$userAnswerInfo['grade1'],
                                'total_score' => (int)$userAnswerInfo['grade'],
                                'answer_right' => $content3['answer_right_num'],
                                'answer_wrong' => $content3['answer_wrong_num'],
                                'timeout_num' => $content3['answer_timeout_num'],
                                'max_question' => $content3['max_question'],
                                'isSuccessful' => (int)$userAnswerInfo['status'] === 1, // 是否通关
                                'score_list' => [
                                    [
                                        'grade' => (int)$userAnswerInfo['grade1'],
                                        'status' => 3
                                    ],
                                    [
                                        'grade' => (int)$userAnswerInfo['grade2'],
                                        'status' => 3
                                    ],
                                    [
                                        'grade' => (int)$userAnswerInfo['grade3'],
                                        'status' => 3
                                    ],
                                    [
                                        'grade' => '一',
                                        'status' => (int)$userAnswerInfo['status'] === 1 ? 0 : 4
                                    ],
                                ],
                            ];
                            break;
                        }
                        if ($index && $option && $index <= $content3['index'])
                        {   // 提交答案
                            $res = $this->nextQuestion($content3, $index, $option, 30);
                            if ($res['updateCache'])
                            {   // 是否更新缓存
                                $userAnswerInfo['content3'] = json_encode($res['content'], JSON_UNESCAPED_UNICODE);
                                if ($res['isOver'])
                                {
                                    $score = $res['content']['answer_right_num'] * $this->questionScore[$userAnswerInfo['level']];//每题5分
                                    $userAnswerInfo['grade3'] = $score; // 第二关分数
                                    $userAnswerInfo['grade'] += $score; // 总分数
                                    $userAnswerInfo['answer_time'] += $res['content']['answer_total_time']; // 答题总时长
                                    // if ($score < $this->levelSuccessScore[$userAnswerInfo['level']]) // 当前关卡 分数
                                    if ($userAnswerInfo['grade'] < $this->levelSuccessScore[$userAnswerInfo['level']]) // 总分
                                    {   // 通关失败
                                        $userAnswerInfo['status'] = 2;//挑战结束
                                    }

                                    // 更新
                                    $userAnswerModel->where('id', $userAnswerInfo['id'])->update([
                                        'update_time' => $this->request->time(),
                                        'grade3' => $userAnswerInfo['grade3'],
                                        'grade' => $userAnswerInfo['grade'],
                                        'content3' => $userAnswerInfo['content3'],
                                        'answer_time' => $userAnswerInfo['answer_time'],
                                        'status' => $userAnswerInfo['status'],
                                        'level' => $userAnswerInfo['level']
                                    ]);

                                    $resData = [
                                        'step' => 31,
                                        'index_score' => (int)$score,
                                        'total_score' => (int)$userAnswerInfo['grade'],
                                        'answer_right' => $res['content']['answer_right_num'],
                                        'answer_wrong' => $res['content']['answer_wrong_num'],
                                        'timeout_num' => $res['content']['answer_timeout_num'],
                                        'max_question' => $res['content']['max_question'],
                                        'isSuccessful' => (int)$userAnswerInfo['status'] === 1, // 是否通关
                                        'score_list' => [
                                            [
                                                'grade' => (int)$userAnswerInfo['grade1'],
                                                'status' => 3
                                            ],
                                            [
                                                'grade' => (int)$userAnswerInfo['grade2'],
                                                'status' => 3
                                            ],
                                            [
                                                'grade' => (int)$userAnswerInfo['grade3'],
                                                'status' => 3
                                            ],
                                            [
                                                'grade' => '一',
                                                'status' => (int)$userAnswerInfo['status'] === 1 ? 0 : 4
                                            ],
                                        ],
                                    ];
                                    $userAnswerModel->setCacheData($userAnswerInfo, $uid); // 更新缓存
                                    $userAnswerModel->changeRankingScore($uid, (int)$userAnswerInfo['grade'], $userAnswerInfo['answer_time']); // 更新排行榜信息
                                    break;
                                } else
                                {
                                    $userAnswerModel->setCacheData($userAnswerInfo, $uid); // 更新缓存
                                }
                            }
                            $resData = $res['resData'];
                        } else
                        {   // 获取题目
                            $isNext = ($this->request->time() - $content3['start_time']) >= $content3['max_answer_time']; // 是否下一题
                            if ($isNext)
                            {   // 下一题
                                $res = $this->nextQuestion($content3, $content3['index'], '', 30);
                                if ($res['updateCache'])
                                {   // 是否更新缓存
                                    $userAnswerInfo['content3'] = json_encode($res['content'], JSON_UNESCAPED_UNICODE);
                                    if ($res['isOver'])
                                    {
                                        $score = $res['content']['answer_right_num'] * $this->questionScore[$userAnswerInfo['level']];//每题5分
                                        $userAnswerInfo['grade3'] = $score; // 第二关分数
                                        $userAnswerInfo['grade'] += $score; // 总分数
                                        $userAnswerInfo['answer_time'] += $res['content']['answer_total_time']; // 答题总时长
                                        // if ($score < $this->levelSuccessScore[$userAnswerInfo['level']]) // 当前关卡 分数
                                        if ($userAnswerInfo['grade'] < $this->levelSuccessScore[$userAnswerInfo['level']]) // 总分
                                        {   // 通关失败
                                            $userAnswerInfo['status'] = 2;//挑战结束
                                        }

                                        // 更新
                                        $userAnswerModel->where('id', $userAnswerInfo['id'])->update([
                                            'update_time' => $this->request->time(),
                                            'grade3' => $userAnswerInfo['grade3'],
                                            'grade' => $userAnswerInfo['grade'],
                                            'content3' => $userAnswerInfo['content3'],
                                            'answer_time' => $userAnswerInfo['answer_time'],
                                            'status' => $userAnswerInfo['status'],
                                            'level' => $userAnswerInfo['level']
                                        ]);

                                        $resData = [
                                            'step' => 31,
                                            'index_score' => (int)$score,
                                            'total_score' => (int)$userAnswerInfo['grade'],
                                            'answer_right' => $res['content']['answer_right_num'],
                                            'answer_wrong' => $res['content']['answer_wrong_num'],
                                            'timeout_num' => $res['content']['answer_timeout_num'],
                                            'max_question' => $res['content']['max_question'],
                                            'isSuccessful' => (int)$userAnswerInfo['status'] === 1, // 是否通关
                                            'score_list' => [
                                                [
                                                    'grade' => (int)$userAnswerInfo['grade1'],
                                                    'status' => 3
                                                ],
                                                [
                                                    'grade' => (int)$userAnswerInfo['grade2'],
                                                    'status' => 3
                                                ],
                                                [
                                                    'grade' => (int)$userAnswerInfo['grade3'],
                                                    'status' => 3
                                                ],
                                                [
                                                    'grade' => '一',
                                                    'status' => (int)$userAnswerInfo['status'] === 1 ? 0 : 4
                                                ],
                                            ],
                                        ];
                                        $userAnswerModel->setCacheData($userAnswerInfo, $uid); // 更新缓存
                                        $userAnswerModel->changeRankingScore($uid, (int)$userAnswerInfo['grade'], $userAnswerInfo['answer_time']); // 更新排行榜信息
                                        break;
                                    } else
                                    {
                                        $userAnswerModel->setCacheData($userAnswerInfo, $uid); // 更新缓存
                                    }
                                }
                                $resData = $res['resData'];
                            } else
                            {   // 当前题
                                $resData = $this->getResultData($content3, $content3['question'][$content3['index'] - 1], 30);
                            }
                        }
                    } else
                    {   // 进入下一关
                        $content3 = json_decode($userAnswerInfo['content3'], true);
                        if (!isset($content3['answer_total_time']) && (int)$userAnswerInfo['status'] === 1)
                        {
                            return show(config('code.error'), '请求异常');
                        }

                        // if ((int)$userAnswerInfo['status'] === 2 || $userAnswerInfo['grade3'] < $this->levelSuccessScore[$userAnswerInfo['level']]) // 当前关卡满足条件
                        if ((int)$userAnswerInfo['status'] === 2 || $userAnswerInfo['grade'] < $this->levelSuccessScore[$userAnswerInfo['level']]) // 总分满足条件
                        {
                            return show(config('code.error'), '当前挑战已结束');
                        }
                        // 初始化第二关答题进度
                        // 获取第四关 随机1题
                        $questionIds = $questionModel->randomGetQuestionId(4, 1, 1);

                        if (!$questionIds)
                        {
                            return show(config('code.error'), '服务异常；请稍后再试～');
                        }

                        $content4 = [
                            'question' => $questionIds,
                            'start_time' => $this->request->time(), // 开始答题时间
                            'index' => 1, // 当前第几题
                            'max_question' => 1,  // 总题目数
                            'max_answer_time' => 14400, // 最大答题时长 4小时
                            'answer' => [] // 答案信息
                        ];
                        $questionId = $questionIds[$content4['index'] - 1];// 获取当前题目ID

                        $userAnswerInfo['content4'] = json_encode($content4, JSON_UNESCAPED_UNICODE);
                        $userAnswerInfo['level']++;
                        $userAnswerModel->setCacheData($userAnswerInfo, $uid); // 更新缓存

                        $resData = $this->getResultData($content4, $questionId, 40);
                    }
                    break;
                case 4:
                    if ($type === 1)
                    {
                        $content4 = json_decode($userAnswerInfo['content4'], true);
                        if ($content4['answer'])
                        {   // 提交过答案了
                            $resData = [
                                'step' => 41,
                                'total_score' => (int)$userAnswerInfo['grade'],
                                'score_list' => [
                                    [
                                        'grade' => (int)$userAnswerInfo['grade1'],
                                        'status' => 3
                                    ],
                                    [
                                        'grade' => (int)$userAnswerInfo['grade2'],
                                        'status' => 3
                                    ],
                                    [
                                        'grade' => (int)$userAnswerInfo['grade3'],
                                        'status' => 3
                                    ],
                                    [
                                        'grade' => $userAnswerInfo['status'] === 2 ? (int)$userAnswerInfo['grade4'] : '一',
                                        'status' => $userAnswerInfo['status'] === 2 ? 3 : 2
                                    ],
                                ],
                            ];
                            break;
                        }
                        if ($option)
                        {   // 回答问题
                            $answerTime = $this->request->time() - $content4['start_time'];// 答题时间

                            if ($answerTime > ($content4['max_answer_time'] + 100))
                            { // 超时100秒提交 则无效
                                $option = '';
                            }
                            $content4['answer'] = [
                                'answer_time' => $answerTime > $content4['max_answer_time'] ? $content4['max_answer_time'] : $answerTime,
                                'option' => $option,
                                'start_time' => date('Y-m-d H:i:s', $content4['start_time']),
                                'tel' => $tel,
                                'love_option' => $loveOption
                            ];
                            $userAnswerInfo['content4'] = json_encode($content4, JSON_UNESCAPED_UNICODE);
                            $userAnswerInfo['answer_time'] += $content4['answer']['answer_time'];
                            $userAnswerInfo['tel'] = $tel;
                            $userAnswerInfo['love_option'] = $loveOption;
                            $userAnswerInfo['status'] = $option ? 1 : 2;
                            // 更新
                            $userAnswerModel->where('id', $userAnswerInfo['id'])->update([
                                'update_time' => $this->request->time(),
                                'content4' => $userAnswerInfo['content4'],
                                'answer_time' => $userAnswerInfo['answer_time'],
                                'tel' => $userAnswerInfo['tel'],
                                'love_option' => $userAnswerInfo['love_option'],
                                'status' => $userAnswerInfo['status'],
                                'level' => $userAnswerInfo['level']
                            ]);
                            if ($userAnswerInfo['status'] === 2)
                            {   // 超时 直接更新用户的分数
                                $userAnswerModel->changeRankingScore($uid, (int)$userAnswerInfo['grade'], $userAnswerInfo['answer_time']); // 更新排行榜信息
                            }
                            $resData = [
                                'step' => 41,
                                'total_score' => (int)$userAnswerInfo['grade'],
                                'score_list' => [
                                    [
                                        'grade' => (int)$userAnswerInfo['grade1'],
                                        'status' => 3
                                    ],
                                    [
                                        'grade' => (int)$userAnswerInfo['grade2'],
                                        'status' => 3
                                    ],
                                    [
                                        'grade' => (int)$userAnswerInfo['grade3'],
                                        'status' => 3
                                    ],
                                    [
                                        'grade' => $userAnswerInfo['status'] === 2 ? (int)$userAnswerInfo['grade4'] : '一',
                                        'status' => $userAnswerInfo['status'] === 2 ? 3 : 2
                                    ],
                                ],
                            ];
                            if ($userAnswerInfo['status'] === 1)
                            { // 发送钉钉消息
                                // $questionId = $content4['question'][0];
                                // $title = $questionModel->getInfoById($questionId, ['title']);
                                // if ($title)
                                // {
                                $this->sendMsg();
                                // }
                            }
                            $userAnswerModel->setCacheData($userAnswerInfo, $uid); // 更新缓存
                            break;
                        } else
                        {   // 获取问题
                            $isNext = ($this->request->time() - $content4['start_time']) >= $content4['max_answer_time']; // 是否下一题
                            if ($isNext)
                            {
                                $content4['answer'] = [
                                    'answer_time' => $content4['max_answer_time'],
                                    'option' => '',
                                    'start_time' => date('Y-m-d H:i:s', $content4['start_time']),
                                    'tel' => '',
                                    'love_option' => ''
                                ];
                                $userAnswerInfo['content4'] = json_encode($content4, JSON_UNESCAPED_UNICODE);
                                $userAnswerInfo['answer_time'] += $content4['max_answer_time'];
                                $userAnswerInfo['status'] = 2;
                                // 更新
                                $userAnswerModel->where('id', $userAnswerInfo['id'])->update([
                                    'update_time' => $this->request->time(),
                                    'content4' => $userAnswerInfo['content4'],
                                    'answer_time' => $userAnswerInfo['answer_time'],
                                    'status' => $userAnswerInfo['status'],
                                    'level' => $userAnswerInfo['level']
                                ]);
                                $userAnswerModel->setCacheData($userAnswerInfo, $uid); // 更新缓存

                                $userAnswerModel->changeRankingScore($uid, (int)$userAnswerInfo['grade'], $userAnswerInfo['answer_time']); // 更新排行榜信息
                                $resData = [
                                    'step' => 41,
                                    'total_score' => (int)$userAnswerInfo['grade'],
                                    'score_list' => [
                                        [
                                            'grade' => (int)$userAnswerInfo['grade1'],
                                            'status' => 3
                                        ],
                                        [
                                            'grade' => (int)$userAnswerInfo['grade2'],
                                            'status' => 3
                                        ],
                                        [
                                            'grade' => (int)$userAnswerInfo['grade3'],
                                            'status' => 3
                                        ],
                                        [
                                            'grade' => $userAnswerInfo['status'] === 2 ? (int)$userAnswerInfo['grade4'] : '一',
                                            'status' => $userAnswerInfo['status'] === 2 ? 3 : 2
                                        ],
                                    ],
                                ];
                                break;
                            }
                            $resData = $this->getResultData($content4, $content4['question'][$content4['index'] - 1], 40);
                        }
                    } else
                    {
                        return show(config('code.error'), '当前挑战已结束');
                    }
                    break;
                default:
                    return show(config('code.error'), '服务异常；请稍后再试～');
            }
        }


        // 返回结果
        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 返回题目信息
     * @param $content array 问题信息
     * @param $qid int  问题ID
     * @param $step int 当前进度 10=>第一关进行中 20=>第二关进行中 30=>第三关进行中 40=>第四关进行中
     * @return array
     * @throws \Exception
     */
    private function getResultData(array $content, int $qid, int $step): array
    {
        $questionInfo = (new ZlAstrExercise())->getInfoById($qid, ['title', 'option_a', 'option_b', 'option_c', 'option_d', 'title_img', 'option_type']);

        $endTime = $content['max_answer_time'] - ($this->request->time() - $content['start_time']);
        $tips = '';
        if ($step === 40)
        {
            $times = $this->request->time() + $endTime;
            $tips = date('Y.m.d H:i:s', $times);
        }

        return [
            'step' => $step,
            'index' => (int)$content['index'],
            'max_question' => (int)$content['max_question'],
            'end_time' => $endTime,
            'title' => htmlspecialchars_decode($questionInfo['title']),
            'topic_option' => [
                [
                    'text' => htmlspecialchars_decode($questionInfo['option_a']),
                    'value' => 'A'
                ],
                [
                    'text' => htmlspecialchars_decode($questionInfo['option_b']),
                    'value' => 'B'
                ],
                [
                    'text' => htmlspecialchars_decode($questionInfo['option_c']),
                    'value' => 'C'
                ],
                [
                    'text' => htmlspecialchars_decode($questionInfo['option_d']),
                    'value' => 'D'
                ]
            ],
            'option_type' => (int)$questionInfo['option_type'],
            'title_img' => $questionInfo['title_img'] ? Env::get('host.photo') . $questionInfo['title_img'] : '',
            'tips' => $tips
        ];
    }

    /**
     * 提交答案 进入下一题 ｜ 计算结果
     * @param $content array 关卡内容
     * @param $index int  当前题目
     * @param $option string 答案
     * @param $setp int 当前进度 10=>第一关进行中 20=>第二关进行中 30=>第三关进行中 40=>第四关进行中
     * @return array
     * @throws \Exception
     */
    private function nextQuestion(array $content, int $index, string $option, int $setp): array
    {
        if ($index < $content['index'])
        {  // 可能情况  网络异常或其他 回答上一题答案
            $updateCache = false;
            if ($index === ($content['index'] - 1) && (($answerTime = $this->request->time() - strtotime($content['answer'][$index]['start_time'])) < ($content['max_answer_time'] + 10)))
            { // 在上一题允许范围内 则 为有效答题
                $content['answer'][$index] = [
                    'answer_time' => $answerTime > $content['max_answer_time'] ? $content['max_answer_time'] : $answerTime, // 当前问题消耗时长
                    'option' => $option, // 答案
                    'start_time' => $content['answer'][$index]['start_time']
                ];
            } else
            { // 无效答题
                if (($this->request->time() - $content['start_time']) >= $content['max_answer_time'])
                { // 当前答案回答时间 也过期
                    $content['answer'][$index] = [
                        'answer_time' => $content['max_answer_time'], // 当前问题消耗时长
                        'option' => '', // 答案
                        'start_time' => date('Y-m-d H:i:s', $content['start_time'])
                    ];
                    $content['index']++;
                    $updateCache = true;
                    if ($content['index'] > $content['max_question'])
                    { // 计算结果 | 返回答题信息
                        // 计算答题信息
                        $content = $this->totalScore($content);
                        return [
                            'content' => $content,
                            'updateCache' => true,
                            'isOver' => true,
                        ];
                    }
                    $content['start_time'] = $this->request->time();
                }
            }

            return [
                'content' => $content,
                'updateCache' => $updateCache,
                'isOver' => false,
                'resData' => $this->getResultData($content, $content['question'][$content['index'] - 1], $setp)
            ];
        } else
        {   // 正常提交答案
            $answerTime = $this->request->time() - $content['start_time'];
            if (!$option || ($answerTime > ($content['max_answer_time'] + 10)))
            {   // 无效答题
                $option = '';
            }
            $content['answer'][$index] = [
                'answer_time' => $answerTime > $content['max_answer_time'] ? $content['max_answer_time'] : $answerTime, // 当前问题消耗时长
                'option' => $option, // 答案
                'start_time' => date('Y-m-d H:i:s', $content['start_time'])
            ];

        }

        if ($content['index'] >= $content['max_question'])
        { // 计算结果 得分
            // 计算答题信息
            $content = $this->totalScore($content);
            return [
                'content' => $content,
                'updateCache' => true,
                'isOver' => true,
            ];
        } else
        {   // 返回下一题
            $content['index']++;
            $content['start_time'] = $this->request->time();
            return [
                'content' => $content,
                'updateCache' => true,
                'isOver' => false,
                'resData' => $this->getResultData($content, $content['question'][$content['index'] - 1], $setp)
            ];
        }
    }

    /**
     * 计算正确结果
     * @param $content
     * @return array
     * @throws \Exception
     */
    private function totalScore(array $content): array
    {
        $questionInfo = (new ZlAstrExercise())->batchGetInfoByIds($content['question'], ['answer', 'option_type']);

        $answerTotalTime = 0; // 答题总时长
        $answerRight = 0;// 正确答题数
        $timeOutNum = 0;// 超时数量
        $answerWrong = 0;// 错误答题数
        $answerRightQuestion = [];// 回答正确的题目 第几题 题目从1开始
        for ($i = 1; $i <= $content['max_question']; $i++)
        {
            if (isset($content['answer'][$i]) && $content['answer'][$i]['option'])
            {   // 如果当前题目回答了
                // 判断是否正确
                if ($questionInfo[$content['question'][$i - 1]]['option_type'] == 1)
                {
                    $answer = strtoupper($content['answer'][$i]['option']);
                    $questionAnswer = strtoupper(trim($questionInfo[$content['question'][$i - 1]]['answer'])); // 问题答案
                } else
                {
                    $answer = explode(',', strtoupper($content['answer'][$i]['option'])); // 答案
                    $questionAnswer = explode(',', strtoupper(trim($questionInfo[$content['question'][$i - 1]]['answer']))); // 问题答案
                    asort($answer);
                    asort($questionAnswer);
                    $answer = array_values($answer);
                    $questionAnswer = array_values($questionAnswer);
                }
                if ($answer === $questionAnswer)
                {
                    $answerRight++;
                    $answerRightQuestion[] = $i;// 当前第几题回答正确
                } else
                {
                    $answerWrong++;
                }
                $answerTotalTime += $content['answer'][$i]['answer_time'];//答题时长
            } else
            {   // 当前题目超时未回答
                $timeOutNum++;
                $answerTotalTime += $content['max_answer_time']; // 答题时长
            }
        }

        $content['answer_total_time'] = $answerTotalTime; // 答题总时长
        $content['answer_right_num'] = $answerRight;    // 答对的题目数量
        $content['answer_timeout_num'] = $timeOutNum;    // 超时数量
        $content['answer_wrong_num'] = $answerWrong;    // 错误答题数
        $content['answer_right_question'] = $answerRightQuestion; // 答对的题目

        return $content;
    }

    /**
     * 查看分数
     * @param array $userAnswerInfo
     * @return array
     */
    private function getScore($userAnswerInfo = []): array
    {
        if ($userAnswerInfo)
        {
            switch ($userAnswerInfo['level'])
            {
                case 1:
                    if (((int)$userAnswerInfo['status'] === 1 && (int)$userAnswerInfo['grade1'] > 0) || (int)$userAnswerInfo['status'] === 2)
                    {
                        $status1 = 3;
                    } else
                    {
                        $status1 = 1;
                    }
                    if ((int)$userAnswerInfo['status'] === 2)
                    {
                        $status2 = 4;
                        $status3 = 4;
                        $status4 = 4;
                    } else
                    {
                        $status2 = 0;
                        $status3 = 0;
                        $status4 = 0;
                    }
                    break;
                case 2:
                    $status1 = 3;
                    if (((int)$userAnswerInfo['status'] === 1 && (int)$userAnswerInfo['grade2'] > 0) || (int)$userAnswerInfo['status'] === 2)
                    {
                        $status2 = 3;
                    } else
                    {
                        $status2 = 1;
                    }
                    if ((int)$userAnswerInfo['status'] === 2)
                    {
                        $status3 = 4;
                        $status4 = 4;
                    } else
                    {
                        $status3 = 0;
                        $status4 = 0;
                    }
                    break;
                case 3:
                    $status1 = 3;
                    $status2 = 3;
                    if (((int)$userAnswerInfo['status'] === 1 && (int)$userAnswerInfo['grade3'] > 0) || (int)$userAnswerInfo['status'] === 2)
                    {
                        $status3 = 3;
                    } else
                    {
                        $status3 = 1;
                    }
                    if ((int)$userAnswerInfo['status'] === 2)
                    {
                        $status4 = 4;
                    } else
                    {
                        $status4 = 0;
                    }
                    break;
                default:
                    $status1 = 3;
                    $status2 = 3;
                    $status3 = 3;
                    $content4 = json_decode($userAnswerInfo['content4'], true);
                    if ((int)$userAnswerInfo['status'] === 2)
                    {
                        $status4 = 3;
                    } elseif ($content4['answer'])
                    {
                        $status4 = 2;
                    } else
                    {
                        $status4 = 1;
                    }
            }

            return [
                'step' => 41,
                'total_score' => (int)$userAnswerInfo['grade'],
                'score_list' => [
                    [
                        'grade' => $status1 === 3 ? (int)$userAnswerInfo['grade1'] : '一',
                        'status' => $status1
                    ],
                    [
                        'grade' => $status2 === 3 ? (int)$userAnswerInfo['grade2'] : '一',
                        'status' => $status2
                    ],
                    [
                        'grade' => $status3 === 3 ? (int)$userAnswerInfo['grade3'] : '一',
                        'status' => $status3
                    ],
                    [
                        'grade' => $status4 === 3 ? (int)$userAnswerInfo['grade4'] : '一',
                        'status' => $status4
                    ],
                ]
            ];
        } else
        {
            return [
                'step' => 41,
                'total_score' => 0,
                'score_list' => [
                    [
                        'grade' => '一',
                        'status' => 0
                    ],
                    [
                        'grade' => '一',
                        'status' => 0
                    ],
                    [
                        'grade' => '一',
                        'status' => 0
                    ],
                    [
                        'grade' => '一',
                        'status' => 0
                    ],
                ]
            ];
        }
    }

    private function sendMsg()
    {
        $env = Env::get('host.name', 'local');
        $title = '[' . $env . ']占星师挑战';
        // $contentMsg = "# 有一条新的待审核消息 \r\n\r\n " .
        //     "题目：{$question} ";
        $contentMsg = "# 有一条新的待审核消息";
        $herfUrl = Env::get('host.admin_domain') . '/admin/zl_astr_exercise_record/index.html';

        $time = time() * 1000;

        // 占星师挑战审核群
        $sec = 'SEC74d6c47c810358afc1c6c56fd2209bfd588ab6a8604455748920b5a419f76f80';
        $sign = urldecode(base64_encode(hash_hmac('sha256', $time . "\n" . $sec, $sec, true)));
        $url = 'https://oapi.dingtalk.com/robot/send?access_token=52d469770cb486b33ce6811f0bd98e671efdbeab76ac15acf67a83aea228b237';// 钉钉推送地址

        $url .= "&timestamp={$time}&sign={$sign}";
        Util::sendDingMsg($url, $title, $contentMsg, 3, $herfUrl);
    }
}
